package com.pactera.jep.service.sys.security.spring.conf;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

/**
 * 处理{@link AccessDeniedException}
 * 
 * @author ghost
 *
 */
@Component
public class AuthenticationAccessDeniedHandler implements AccessDeniedHandler {

	private final static Logger logger = LoggerFactory.getLogger(AuthenticationAccessDeniedHandler.class);

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException, ServletException {
		logger.debug("来自{}的用户{}对{}的请求被拒绝，原因是：{}", request.getRemoteHost(), request.getRemoteUser(),
				request.getRequestURI(), accessDeniedException.getMessage());
		response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		response.setContentType("application/json;charset=UTF-8");
		try (PrintWriter writer = response.getWriter()) {
			String message = "{\"success\":\"false\", \"message\":\"你没有访问此链接的权限！\"}";
			writer.write(message);
			writer.flush();
		}
	}

}
